using System;
using System.Collections.Generic;
using NUnit.Framework;
using ProjectEuler.Core.Helpers;

namespace ProjectEuler.Core
{
    public class Problem12 : IProjectEulerProblem
    {
        protected int NthTriangleNumber(int n)
        {
            var sum = 0;
            for(int i=1;i<=n;i++)
            {
                sum += i;
            }
            return sum;
        }

        protected int FirstTriangleNumberWithNFactors(int n)
        {
            for(int i=0;i<int.MaxValue;i++)
            {
                var triangleNumber = NthTriangleNumber(i);
                if (MathHelper.FactorsOf(triangleNumber).Count > n)
                {
                    return triangleNumber;
                }
            }
            throw new OverflowException("Overflow!");
        }

        public int Number
        {
            get { return 12; }
        }

        public string Description
        {
            get { return "What is the value of the first triangle number to have over five hundred divisors?"; }
        }

        public string Answer
        {
            get { return FirstTriangleNumberWithNFactors(500).ToString(); }
        }
    }

    [TestFixture]
    public class Problem12Tests : Problem12
    {
        [Test]
        public void Finds_28_as_the_first_triangle_number_with_over_five_factors()
        {
            var sixth = NthTriangleNumber(6);
            Assert.LessOrEqual(MathHelper.FactorsOf(sixth).Count, 5);

            var seventh = NthTriangleNumber(7);
            Assert.Greater(MathHelper.FactorsOf(seventh).Count, 5);
        }
    }
}